<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :size="size"
    :style="{ width: width }"
    @change="handleChange"
    @clear="handleClear"
  >
    <el-option
      v-for="pond in flatPondOptions"
      :key="pond.id"
      :label="pond.label"
      :value="pond.id"
    />
  </el-select>
</template>

<script setup name="PondSelect">
import { ref, computed, watch, onMounted } from 'vue'
import { pondOptions, listPond } from '@/api/pond/pond'

// Props定义
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: undefined
  },
  deptId: {
    type: [String, Number],
    default: undefined
  },
  placeholder: {
    type: String,
    default: '请选择鱼塘'
  },
  clearable: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  size: {
    type: String,
    default: 'default'
  },
  width: {
    type: String,
    default: '100%'
  }
})

// Emits定义
const emit = defineEmits(['update:modelValue', 'change', 'clear'])

// 响应式数据
const pondTreeData = ref([])
const selectedValue = ref(props.modelValue)

// 计算属性：扁平化的鱼塘选项（只包含叶节点）
const flatPondOptions = computed(() => {
  return flattenTreeToLeafNodes(pondTreeData.value)
})

/**
 * 将树形数据扁平化，只保留叶节点
 * @param {Array} treeData 树形数据
 * @param {String} parentPath 父级路径，用于构建完整的显示名称
 * @returns {Array} 扁平化的叶节点数组
 */
function flattenTreeToLeafNodes(treeData, parentPath = '') {
  const result = []
  
  if (!Array.isArray(treeData)) {
    return result
  }
  
  treeData.forEach(node => {
    // 构建当前节点的完整路径名称
    const nodeName = node.pondName || node.name || node.label || `节点${node.id || node.pondId}`
    const currentPath = parentPath ? `${parentPath} / ${nodeName}` : nodeName
    
    // 判断是否为叶节点（没有子节点或子节点为空）
    const hasChildren = node.children && Array.isArray(node.children) && node.children.length > 0
    
    if (!hasChildren) {
      // 叶节点，添加到结果中
      result.push({
        id: node.pondId || node.id,
        label: currentPath,
        value: node.pondId || node.id,
        pondName: nodeName,
        fullPath: currentPath,
        originalData: node
      })
    } else {
      // 非叶节点，递归处理子节点
      const childNodes = flattenTreeToLeafNodes(node.children, currentPath)
      result.push(...childNodes)
    }
  })
  
  return result
}

/**
 * 获取鱼塘选项数据
 */
async function fetchPondOptions() {
  try {
    let response
    if (props.deptId) {
      // 如果有部门ID，使用listPond接口获取指定部门的鱼塘
      const params = {
        pageNum: 1,
        pageSize: 1000, // 设置一个较大的值来获取所有数据
        deptId: props.deptId
      }
      response = await listPond(params)
      pondTreeData.value = response.rows || []
    } else {
      // 如果没有部门ID，使用pondOptions接口获取所有鱼塘
      response = await pondOptions()
      pondTreeData.value = response.rows || response.data || []
    }
  } catch (error) {
    console.error('获取鱼塘选项失败:', error)
    pondTreeData.value = []
  }
}

/**
 * 处理选择变化
 */
function handleChange(value) {
  selectedValue.value = value
  emit('update:modelValue', value)
  
  // 找到选中的鱼塘完整信息
  const selectedPond = flatPondOptions.value.find(pond => pond.id === value)
  emit('change', value, selectedPond)
}

/**
 * 处理清空
 */
function handleClear() {
  selectedValue.value = undefined
  emit('update:modelValue', undefined)
  emit('clear')
}

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  selectedValue.value = newValue
}, { immediate: true })

// 监听deptId变化，重新获取数据并清空选中值
watch(() => props.deptId, (newDeptId, oldDeptId) => {
  // 当deptId发生变化时，清空当前选中的值
  if (newDeptId !== oldDeptId) {
    selectedValue.value = undefined
    emit('update:modelValue', undefined)
    emit('clear')
  }
  // 重新获取鱼塘数据
  fetchPondOptions()
}, { immediate: false })

// 组件挂载时获取数据
onMounted(() => {
  fetchPondOptions()
})
</script>